package com.eco.fishway.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.db.dto.FishStatisticsDTO;
import com.eco.db.entity.Record;

import com.eco.db.mapper.RecordMapper;
import com.eco.db.vo.FishStatisticsVO;
import com.eco.fishway.constant.StatisticsConstants;
import com.eco.fishway.service.RecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xulinyu
 * @since 2024-07-18
 */
@Service
public class RecordServiceImpl extends ServiceImpl<RecordMapper, Record> implements RecordService {

    private final RecordMapper recordMapper;

    public RecordServiceImpl(RecordMapper recordMapper) {
        this.recordMapper = recordMapper;
    }

    @Override
    public Object numberStatistics(FishStatisticsDTO dto) {
        List<FishStatisticsVO> list = recordMapper.numberStatistics(new QueryWrapper<Record>()
                .select(numberSelectSql(dto.getType()))
                // 时间范围查询
                .between("recordTime", dto.getBeginDate(), dto.getEndDate())
                .groupBy("code", "name"),dto.getBeginDate(),dto.getEndDate());
        return list.stream().collect(Collectors.groupingBy(FishStatisticsVO::getCode, LinkedHashMap::new,Collectors.toList()));
    }

    /**
     * 根据统计类型返回sql
     * @param type
     * @return
     */
    private String numberSelectSql(String type) {
        String sql = "";
        switch (type) {
            // 小时统计
            case StatisticsConstants.HOUR:
                sql = "DATE_FORMAT(recordTime, '%Y年%c月%e日%k时') code, category name, count(*) value";
                break;
            // 年月日统计
            case StatisticsConstants.DAY:
                sql = "DATE_FORMAT(recordTime, '%Y年%c月%e日') code, category name, count(*) value";
                break;
            // 月度统计
            case StatisticsConstants.MONTH:
                sql = "DATE_FORMAT(recordTime, '%Y年%c月') code, category name, count(*) value";
                break;
            // 季度统计
            case StatisticsConstants.QUARTER:
                sql = "CONCAT(YEAR(recordTime) ,QUARTER(natural_point)) code, category name, count(*) value";
                break;
            // 年度统计
            case StatisticsConstants.YEAR:
                sql = "YEAR(recordTime) code, category name, count(*) value";
                break;
        }
        return sql;
    }
}
